package com.jiaolong.service;

import com.jiaolong.converter.OrderConverter;
import com.jiaolong.domain.OrderDo;
import com.jiaolong.dto.OrderDto;
import com.jiaolong.utils.QRConfigUtil;
import com.jiaolong.utils.RedirectUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class JiaolongpayService {

    @Resource
    private AlipayService alipayService;

    @Resource
    OrderService orderService;

    /**
     * 新增订单
     * @param orderDto
     */
    public void getQRCode(OrderDto orderDto, HttpServletResponse servletResponse) {
        String mchOrderNo = orderService.saveOrder(orderDto);
        // 返回给前端的二维码包含的信息
        String content = "http://1a702e43.r26.cpolar.top/api/jiaolongpay/payScanCode/" + mchOrderNo;
        try {
            QRConfigUtil.createCodeToOutputStream(content, servletResponse.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void paymentWay(Long mchOrderNo, HttpServletRequest request, HttpServletResponse response) {
        // 查询订单信息
        OrderDo orderDo = orderService.getOrderByMchOrderNo(mchOrderNo);
        if(orderDo.getComplete() == 1) {
            // 已成功支付，不能重复支付
            return;
        }
        OrderDto dto = OrderConverter.INSTANCE.do2Dto(orderDo);
        String url = null;
        // 获取请求UA
        String userAgent = request.getHeader("user-agent");
        System.out.println(userAgent);
        // 支付宝扫码
        if(userAgent.contains("AlipayClient")) {
            url = alipayService.payScanCode(dto, null);
        } //else if(userAgent.contains("WeChat")){

        //}
        RedirectUtil.httpRedirect(response, url);
    }

}
